<?php

class Parte_Processo extends DataMapper {
	
    var $table = 'partes_processos';
	var $has_one = array("processo","parte");
	
	function __construct($id = NULL)
    {
        parent::__construct($id);
    }
	
	/*public function historico($id){

        $result = $this->db->query("
		SELECT 
		DATE_FORMAT(processos.dt_cadastro,'%d/%m/%Y %T') as dt_cadastro, 
		processos.numeroprocesso, 
		tipoprocessos.nomeprocesso, 
		nome_parte, 
		tipos_parte, 
		processos.`status`, 
		usuarios.nome_completo, 
		processos.id as processos_id
		FROM partes_processos
		LEFT JOIN processos ON processos.id = partes_processos.processo_id
		LEFT JOIN tipoprocessos ON tipoprocessos.id = processos.tipoprocesso_id
		LEFT JOIN usuarios ON usuarios.id = processos.usuario_id
		LEFT JOIN partes ON partes.id = partes_processos.parte_id
		WHERE partes_processos.parte_id = '".$id."'	
		");
		
		$p = new Parte_Processo();
		$p->_process_query($result);
		
		return $p;
    }*/
	public function pluck ( $a, $prop )	{
		$out = array();

		for ( $i=0, $len=count($a) ; $i<$len ; $i++ ) {
			$out[] = $a[$i][$prop];
		}

		return $out;
	}
	public function historico(){
		
		$table = "partes_processos";
		
		$columns = array(
			array( 'db' => 'processos.numeroprocesso','dt' => 0 ),
			array( 'db' => 'DATE_FORMAT(processos.dt_cadastro,"%d/%m/%Y %T") as dt_cadastro','dt' => 1 ),
			array( 'db' => 'nomeprocesso','dt' => 2 ),
			array( 'db' => 'tipos_parte','dt' => 3 ),
			array( 'db' => 'processos.`status`','dt' => 4 ),
			array( 'db' => 'usuarios.nome_completo','dt' => 5 ),
			array( 'db' => 'processos.id as processos_id','dt' => 6 )
		);
		
		$columnsaux = array(
			array( 'db' => 'processos.numeroprocesso','dt' => 0 ),
			array( 'db' => 'processos.dt_cadastro','dt' => 1 ),
			array( 'db' => 'nomeprocesso','dt' => 2 ),
			array( 'db' => 'tipos_parte','dt' => 3 ),
			array( 'db' => 'processos.`status`','dt' => 4 ),
			array( 'db' => 'usuarios.nome_completo','dt' => 5 ),
			array( 'db' => 'processos.id as processos_id','dt' => 6 )
		);
		
		//**********************************************************************
		// LIMITE
		//**********************************************************************
		$sLimit = "";
		if ( isset( $_GET['start'] ) && $_GET['length'] != '-1')
		{
			$sLimit = "LIMIT ".intval( $_GET['start'] ).", ".intval( $_GET['length'] );
		}
		
		
		//**********************************************************************
		// ORDENAÇÃO
		//**********************************************************************
		$order = '';
	
		if ( isset($_GET['order']) && count($_GET['order']) ) {
			$orderBy = array();
			$dtColumns = $this->pluck( $columnsaux, 'dt' );

			for ( $i=0, $ien=count($_GET['order']) ; $i<$ien ; $i++ ) {
				// Convert the column index into the column data property
				$columnIdx = intval($_GET['order'][$i]['column']);
				$requestColumn = $_GET['columns'][$columnIdx];

				$columnIdx = array_search( $requestColumn['data'], $dtColumns );
				$column = $columnsaux[ $columnIdx ];

				if ( $requestColumn['orderable'] == 'true' ) {
					$dir = $_GET['order'][$i]['dir'] === 'asc' ?
						'ASC' :
						'DESC';

					$orderBy[] = ''.$column['db'].' '.$dir;
				}
			}

			$order = 'ORDER BY '.implode(', ', $orderBy);
		}
		
		$globalSearch = array();
		$columnSearch = array();
		$dtColumns = $this->pluck( $columnsaux, 'dt' );


		if ( isset($_GET['search']) && $_GET['search']['value'] != '' ) {
			$str = $_GET['search']['value'];

			for ( $i=0, $ien=count($_GET['columns']) ; $i<$ien ; $i++ ) {
				$requestColumn = $_GET['columns'][$i];
				$columnIdx = array_search( $requestColumn['data'], $dtColumns );
				$column = $columnsaux[ $columnIdx ];

				if ( $requestColumn['searchable'] == 'true' ) {
					//$binding = '%'.$str.'%';
					$globalSearch[] = " ".$column['db']." LIKE '%".$str."%'";
					
				}
			}
		}

		$status = '';
		
		//**********************************************************************
		// WHERE
		//**********************************************************************
		// Individual column filtering
		
		for ( $i=0, $ien=count($_GET['columns']) ; $i<$ien ; $i++ ) {
			$requestColumn = $_GET['columns'][$i];
			$columnIdx = array_search( $requestColumn['data'], $dtColumns );
			$column = $columnsaux[ $columnIdx ];

			$str = $requestColumn['search']['value'];

			if ( $requestColumn['searchable'] == 'true' && $str != '' ) {
				//$binding = '%'.$str.'%';
				$columnSearch[] = " ".$column['db']." LIKE '%".$str."%'";
			}
		}

		// Combine the filters into a single string
		$where = '';
		
		if ( count( $globalSearch ) ) {
			$where = '('.implode(' OR ', $globalSearch).')';

				$status = " partes_processos.parte_id = '".$_GET["id"]."'";
				$where .= " AND ".$status;

		}

		if ( count( $columnSearch ) ) {
			$where = $where === '' ? 
				implode(' AND ', $columnSearch) :
				$where .' AND '. implode(' AND ', $columnSearch);
		}

		
		if ( $where !== '' ) {
			$where = 'WHERE '.$where;
		}else{

				$status = " partes_processos.parte_id = '".$_GET["id"]."'";
				$where = 'WHERE '.$status;

		}
		
	
        $result = $this->db->query("
			SELECT 
			".implode(", ", $this->pluck($columns, 'db'))." 
			FROM $table  
			LEFT JOIN processos ON processos.id = partes_processos.processo_id 
			LEFT JOIN tipoprocessos ON tipoprocessos.id = processos.tipoprocesso_id 
			LEFT JOIN usuarios ON usuarios.id = processos.usuario_id 
			LEFT JOIN partes ON partes.id = partes_processos.parte_id 
			$where  
			$order   
			$sLimit	"
		);
		
		/*echo "
			SELECT 
			".implode(", ", $this->pluck($columns, 'db'))." 
			FROM $table  
			LEFT JOIN processos ON processos.id = partes_processos.processo_id 
			LEFT JOIN tipoprocessos ON tipoprocessos.id = processos.tipoprocesso_id 
			LEFT JOIN usuarios ON usuarios.id = processos.usuario_id 
			LEFT JOIN partes ON partes.id = partes_processos.parte_id  
			$where  
			$order   
			$sLimit	
			";*/
	
		$s1 = new Parte_Processo();
		$s1->_process_query($result);
		
		$result = $this->db->query("SELECT FOUND_ROWS() as recordsTotal");
		
		$s2 = new Parte_Processo();
		
		$s2->_process_query($result);
		$recordsTotal = '';
		
		foreach($s2 as $u){
			$recordsTotal = $u->recordsTotal;
		}
		
		
		$result = $this->db->query("SELECT COUNT(id) as recordsFiltered FROM partes_processos");
		
		$s3 = new Parte_Processo();
		
		$recordsFiltered = '';
		$s3->_process_query($result);
		foreach($s3 as $u){
			$recordsFiltered = $u->recordsFiltered;
		}
		
		$dados = array();
		$vetor = array();
		
		$vetor["draws"] = $_GET['draw'];
		$vetor["recordsTotal"] = $recordsTotal;
		$vetor["recordsFiltered"] = $recordsFiltered;
		

		
		foreach($s1 as $u){
			$aux = array();

			$aux[] = $u->numeroprocesso;
			$aux[] = $u->dt_cadastro;
			$aux[] = $u->nomeprocesso;
			if($u->tipos_parte == 'A'){
				$aux[] =  'AUTOR';
			}else{
				$aux[] =  'RÉU';
			}
			
			if($u->status == '1'){
				$aux[] =  '<a style="padding: 1px 1px 1px 1px;"  href="#" class="btn btn-success btn-xs">ATIVO</a>';
			}else{
				$aux[] =  '<a style="padding: 1px 1px 1px 1px;"  href="#" class="btn btn-danger btn-xs">ARQUIVADO</a>';
			}
			$aux[] = $u->nome_completo;
			$aux[] = '<a data-toggle="modal" href="'.base_url('index.php/processos/info/'.$u->processos_id).'" class="btn btn-success btn-xs"><span class="glyphicon glyphicon-plus"></span>Detalhes</a>';

		
			array_push($dados,$aux);
		}
		
		$vetor["data"] = $dados;
		
		
		echo json_encode($vetor);
	}
	public function acompanhamento($id, $tipo){

        $result = $this->db->query("
		SELECT nome_parte, cpfcnpj, endereco, telefone,cidade, estado
		FROM partes_processos
		left join partes on partes.id = partes_processos.parte_id
		WHERE processo_id='$id' AND tipos_parte='$tipo';
		");
		
		$p = new Parte_Processo();
		$p->_process_query($result);
		
		return $p;
    }
	
}

/* End of file processo.php */
/* Location: ./application/models/processo.php */
